package com.tools.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Utils {

	public static final int OXFF = 255;
	public static final int OX10 = 16;

	private MD5Utils() {
	}

	public static String crypt(String str) throws NoSuchAlgorithmException {
		if (str == null || str.length() == 0)
			throw new IllegalArgumentException(
					"String to encript cannot be null or zero length");
		StringBuffer hexString = new StringBuffer();
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(str.getBytes());
		byte hash[] = md.digest();
		byte abyte0[];
		int j = (abyte0 = hash).length;
		for (int i = 0; i < j; i++) {
			byte aHash = abyte0[i];
			if ((0xff & aHash) < 16)
				hexString.append("0").append(Integer.toHexString(0xff & aHash));
			else
				hexString.append(Integer.toHexString(0xff & aHash));
		}

		return hexString.toString();
	}

	public static final String MD5(String s) {
		try {
			char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
					'9', 'a', 'b', 'c', 'd', 'e', 'f' };
			char str[];
			byte btInput[] = s.getBytes();
			MessageDigest mdInst;

			mdInst = MessageDigest.getInstance("MD5");
			mdInst.update(btInput);
			byte md[] = mdInst.digest();
			int j = md.length;
			str = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}

			return new String(str);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
